<template>
  <div class="option-pages">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <span class="title-icon">📚</span>
          {{ isEdit ? '编辑知识库' : '创建知识库' }}
        </h1>
        <p class="page-description">配置您的AI知识库，上传相关文档以增强AI助手的专业能力</p>
      </div>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
      <a-form ref="formRef" :model="formState" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol"
        autocomplete="off" @finish="onFinish" @finishFailed="onFinishFailed">

        <!-- 基本信息区块 -->
        <div class="form-section">
          <div class="section-header">
            <h3 class="section-title">
              <span class="section-icon">⚙️</span>
              基本信息
            </h3>
            <p class="section-description">设置知识库的基本信息和描述</p>
          </div>

          <div class="section-content">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="知识库名称" name="name">
                  <a-input v-model:value="formState.name" placeholder="请输入知识库名称" size="large" class="form-input" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item label="描述" name="description">
                  <a-textarea v-model:value="formState.description" placeholder="请输入知识库描述，详细说明该知识库的用途和包含的内容" :rows="4"
                    size="large" class="form-textarea" show-count :maxlength="500" />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>

        <!-- 文档管理区块 -->
        <div class="form-section">
          <div class="section-header">
            <h3 class="section-title">
              <span class="section-icon">📄</span>
              文档管理
            </h3>
            <p class="section-description">上传相关文档来构建知识库内容（支持PDF、Word、TXT格式，单个文件不超过10MB）</p>
          </div>

          <div class="option-column">

            <a-upload-dragger v-model:fileList="fileList1" name="file" :multiple="false" :max-count="1"
              :customRequest="customUpload1" @change="handleChange1" @drop="handleDrop1">
              <p class="ant-upload-drag-icon">
                <CloudUploadOutlined />
              </p>
              <p class="ant-upload-hint">
                将模型拖拽到此，或单击<span class="blue">直接上传</span>
              </p>
            </a-upload-dragger>
          </div>
        </div>

        <!-- 操作按钮区域 -->
        <div class="form-actions">
          <a-space size="large">
            <a-button size="large" @click="handleCancel" class="cancel-button">
              取消
            </a-button>
            <a-button type="primary" html-type="submit" :loading="loading" size="large" class="submit-button">
              <template #icon>
                <span v-if="!loading">{{ isEdit ? '💾' : '✨' }}</span>
              </template>
              {{ isEdit ? '更新知识库' : '创建知识库' }}
            </a-button>
          </a-space>
        </div>
      </a-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import { useGlobalStore } from '@/store/modules/global';
import { CloudUploadOutlined } from "@ant-design/icons-vue";
import knowledgeApi from '@/api/knowledge';
import systemApi from "@/api/system";
const router = useRouter();
const route = useRoute();
const store = useGlobalStore();

const formRef = ref();
const loading = ref(false);
const isEdit = ref(false);
const fileList = ref([]);
const fileList1 = ref([]);
const labelCol = { span: 4 };
const wrapperCol = { span: 20 };

const formState = reactive({
  name: '',
  description: '',
  enabled: true,
  model_files: []
});

const rules = {
  name: [
    { required: true, message: '请输入知识库名称', trigger: 'blur' },
    { min: 2, max: 50, message: '知识库名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  enabled: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  description: [
    { max: 500, message: '描述不能超过 500 个字符', trigger: 'blur' }
  ]
};
// 自定义上传函数1 - 设备模型
const customUpload1 = async (options) => {
  const { file, onSuccess, onError } = options;
  try {
    const response = await systemApi.FileUpload(file);
    if (response && response.url) {
      onSuccess(response, file);
    } else {
      onError(new Error('上传失败'));
    }
  } catch (error) {
    console.error('模型文件上传失败:', error);
    onError(error);
  }
};
const handleChange1 = (info) => {
  const status = info.file.status;
  if (status !== "uploading") {
    console.log(info.file, info.fileList);
  }
  if (status === "done") {
    message.success(`${info.file.name} 模型文件上传成功`);
    // 将文件对象添加到 model_files 数组
    console.log(info.file.response, '将文件对象添加到 mo      del_files 数组')
    if (info.file.response && info.file.response.url) {
      formState.model_files.push({
        ...info.file,
        url: info.file.response.url
      });
    }
  } else if (status === "error") {
    message.error(`${info.file.name} 模型文件上传失败`);
  }
};
function handleDrop1(e) {
  console.log('Dropped model files', e.dataTransfer.files);
}
onMounted(() => {
  const id = route.query.id;
  if (id) {
    isEdit.value = true;
    loadData(id);
  }
});

const loadData = async (id) => {
  try {
    loading.value = true;
    const response = await knowledgeApi.AiDocFetchModel({ ai_doc_id: id });

    if (response && response.ai_doc_id) {
      // 反显基本信息
      formState.name = response.name || '';
      formState.description = response.description || '';
      formState.enabled = response.enabled !== undefined ? response.enabled : true;

      // 反显文件信息
      if (response.model_file_url) {
        fileList1.value = [{
          uid: '-1',
          name: response.name || '模型文件',
          status: 'done',
          url: response.model_file_url,
          response: { url: response.model_file_url }
        }];
      }
    } else {
      message.error('获取数据失败');
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

const onFinish = async (values) => {
  try {
    loading.value = true;
    console.log('表单数据:', values);

    if (isEdit.value) {
      // 更新逻辑
      try {
        const updateData = {
          ai_doc_id: route.query.id,
          name: values.name,
          description: values.description,
          created: new Date().toISOString()
        };

        const response = await knowledgeApi.AiDocUpdate(updateData);

        if (response) {
          message.success('知识库更新成功！');
          router.push('ai-knowledge-management');
        } else {
          message.error(response?.message || '更新失败，请重试');
        }
      } catch (error) {
        console.error('更新知识库失败:', error);
        message.error('更新失败，请检查网络连接或联系管理员');
      }
    } else {
      // 创建逻辑
      const createData = {
        name: values.name,
        description: values.description,
        created: new Date().toISOString()
      };

      const response = await knowledgeApi.AiDocCreate(createData);
      console.log(response, '创建知识库')
      if (response && response.ai_doc_id) {
        message.success('知识库创建成功！');
        router.push('ai-knowledge-management');
      } else {
        message.error(response?.message || '创建失败，请重试');
        return;
      }
    }
  } catch (error) {
    console.error('创建失败:', error);
    message.error(isEdit.value ? '更新失败' : '创建失败');
  } finally {
    loading.value = false;
  }
};

const onFinishFailed = (errorInfo) => {
  console.log('表单验证失败:', errorInfo);
};

const handleCancel = () => {
  router.back();
};

const beforeUpload = (file) => {
  const isValidType = file.type === 'application/pdf' ||
    file.type === 'application/msword' ||
    file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
    file.type === 'text/plain';

  if (!isValidType) {
    message.error('只能上传 PDF、Word 或 TXT 文件!');
    return false;
  }

  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('文件大小不能超过 10MB!');
    return false;
  }

  return false; // 阻止自动上传
};

const handleRemove = (file) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
};

// 获取模型文件URL
const getModelFileUrl = () => {
  if (fileList1.value && fileList1.value.length > 0) {
    const file = fileList1.value[0];
    return file.response?.url || file.url || '';
  }
  return '';
};
</script>

<style lang="less" scoped>
.option-pages {
  min-height: 100vh;
  background: #fff;
  padding: 24px;
  overflow-y: auto;

  // 页面头部样式
  .page-header {
    background: #fff;
    border-bottom: 1px solid #f0f0f0;
    padding: 32px 24px;
    margin-bottom: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .header-content {
      max-width: 1200px;
      margin: 0 auto;
      text-align: center;

      .page-title {
        font-size: 32px;
        font-weight: 700;
        color: #2c3e50;
        margin: 0 0 12px 0;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;

        .title-icon {
          font-size: 36px;
          animation: bounce 2s infinite;
        }
      }

      .page-description {
        font-size: 16px;
        color: #64748b;
        margin: 0;
        line-height: 1.6;
      }
    }
  }

  // 表单容器样式
  .form-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 0 40px;
  }

  // 表单区块样式
  .form-section {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    margin-bottom: 24px;
    overflow: hidden;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
    }

    .section-header {
      background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
      padding: 24px 32px;
      border-bottom: 1px solid #e2e8f0;

      .section-title {
        font-size: 20px;
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 8px 0;
        display: flex;
        align-items: center;
        gap: 12px;

        .section-icon {
          font-size: 24px;
        }
      }

      .section-description {
        font-size: 14px;
        color: #64748b;
        margin: 0;
        line-height: 1.5;
      }
    }

    .section-content {
      padding: 32px;
    }
  }

  // 表单控件样式
  .form-input,
  .form-textarea {
    border-radius: 8px;
    transition: all 0.3s ease;

    &:focus {
      box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
      border-color: #1890ff;
    }
  }

  // 文档上传区域样式
  .document-upload-area {
    border: 2px dashed #d1d5db;
    border-radius: 12px;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    transition: all 0.3s ease;
    overflow: hidden;

    &:hover {
      border-color: #1890ff;
      background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
      transform: translateY(-1px);
    }

    .upload-content {
      padding: 40px 24px;
      text-align: center;
      position: relative;

      .upload-icon {
        font-size: 48px;
        color: #94a3b8;
        margin-bottom: 16px;
        transition: all 0.3s ease;
      }

      .upload-text {
        margin-bottom: 24px;

        .upload-title {
          font-size: 18px;
          font-weight: 600;
          color: #374151;
          margin: 0 0 8px 0;
        }

        .upload-hint {
          font-size: 14px;
          color: #6b7280;
          margin: 0;
        }
      }

      .upload-button {
        border-radius: 8px;
        height: 48px;
        padding: 0 32px;
        font-weight: 500;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 20px rgba(24, 144, 255, 0.3);
        }
      }
    }

    &:hover .upload-icon {
      color: #1890ff;
      transform: scale(1.1);
    }
  }

  // 操作按钮区域样式
  .form-actions {
    text-align: center;
    padding: 32px;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    margin-top: 24px;

    .cancel-button {
      height: 48px;
      padding: 0 32px;
      border-radius: 8px;
      font-weight: 500;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
    }

    .submit-button {
      height: 48px;
      padding: 0 32px;
      border-radius: 8px;
      font-weight: 500;
      background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
      border: none;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 20px rgba(24, 144, 255, 0.4);
        background: linear-gradient(135deg, #40a9ff 0%, #1890ff 100%);
      }

      &:active {
        transform: translateY(0);
      }
    }
  }
}

// 深度样式覆盖
:deep(.ant-form-item-label) {
  font-weight: 600;
  color: #374151;

  >label {
    font-size: 15px;
    height: auto;
    line-height: 1.5;
  }
}

:deep(.ant-form-item) {
  margin-bottom: 24px;
}

:deep(.ant-input),
:deep(.ant-input-affix-wrapper) {
  border-radius: 8px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;

  &:hover {
    border-color: #9ca3af;
  }

  &:focus,
  &.ant-input-affix-wrapper-focused {
    border-color: #1890ff;
    box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
  }
}

:deep(.ant-input-lg) {
  height: 48px;
  font-size: 16px;
}

:deep(.ant-switch) {
  &.ant-switch-checked {
    background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
  }
}

:deep(.ant-upload-list) {
  margin-top: 20px;

  .ant-upload-list-item {
    border-radius: 8px;
    border: 1px solid #e5e7eb;
    background: #f9fafb;
    transition: all 0.3s ease;

    &:hover {
      background: #f3f4f6;
      border-color: #d1d5db;
    }
  }
}

:deep(.ant-upload) {
  width: 100%;
}

// 动画效果
@keyframes bounce {

  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateY(0);
  }

  40% {
    transform: translateY(-10px);
  }

  60% {
    transform: translateY(-5px);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .option-pages {
    .page-header {
      padding: 24px 16px;

      .page-title {
        font-size: 24px;
        flex-direction: column;
        gap: 8px;
      }

      .page-description {
        font-size: 14px;
      }
    }

    .form-container {
      padding: 0 16px 24px;
    }

    .form-section {
      .section-header {
        padding: 20px 24px;

        .section-title {
          font-size: 18px;
        }
      }

      .section-content {
        padding: 24px 20px;
      }
    }

    .form-actions {
      padding: 24px 20px;

      .ant-space {
        width: 100%;
        flex-direction: column;

        .ant-space-item {
          width: 100%;

          .ant-btn {
            width: 100%;
          }
        }
      }
    }
  }
}
</style>